package com.sanjiahantang.youjiaclient.module.evaluate.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.BitmapUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.module.common.beans.FileBean;
import com.sanjiahantang.youjiaclient.module.evaluate.beans.RoleBean;
import com.sanjiahantang.youjiaclient.module.evaluate.presenters.MeEvaluatePresenter;
import com.sanjiahantang.youjiaclient.module.evaluate.views.MeEvaluateView;
import com.sanjiahantang.youjiaclient.module.goods.beans.GoodsBean;
import com.sanjiahantang.youjiaclient.module.me.order.beans.ServiceListBean;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * 设计师评价
 * Created by zy on 2017/11/28.
 */

public class EvaluateServiceActivity extends BaseMvpActivity<MeEvaluateView,MeEvaluatePresenter> implements MeEvaluateView, View.OnClickListener {

    private ServiceListBean.Data serviceData;
    private ImageView ivTargetPhoto1,ivTargetPhoto2;
    private TextView txtTargetJob1,txtTargetName1,txtTargetJob2,txtTargetName2;
    private int maxId1,maxId2;
    private EditText txtContent1,txtContent2;
    private GridView gvImageList1,gvImageList2;
    private BaseAdapter adapter1,adapter2;
    private List<GoodsBean.Image> imageList1,imageList2;
    private LayoutInflater inflater;
    private RatingBar ratingBar1,ratingBar2;
    private RoleBean.Data role1,role2;
    private int type; //0 設計師 1 項目經理 監理
    private View panel2;
    private int currentIndex;

    private SelectPhotoPopupwindow photoPopupwindow;
    private View rootView;

    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int UPLOAD_PIC = 3;
    private static final int PHOTO_GRAPH = 0xF, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;

    @Override
    public void loadData(RecyclerView.Adapter adapter) {

    }

    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    @Override
    public MeEvaluatePresenter initPresenter() {
        return new MeEvaluatePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_service_evaluate);
        TextView title = (TextView) findViewById(R.id.title);
        title.setText("服务评价");
        findViewById(R.id.fl_Left).setOnClickListener(this);
        rootView = findViewById(R.id.rootView);

        serviceData = (ServiceListBean.Data) getIntent().getSerializableExtra(KEY_PARAM);
        ivTargetPhoto1 = (ImageView) findViewById(R.id.ivTargetPhoto1);
        txtTargetJob1 = (TextView) findViewById(R.id.txtTargetJob1);
        txtTargetName1 = (TextView) findViewById(R.id.txtTargetName1);
        txtContent1 = (EditText) findViewById(R.id.txtContent1);
        gvImageList1 = (GridView) findViewById(R.id.gvImageList1);
        imageList1 = new ArrayList<>();
        inflater = LayoutInflater.from($this);
        ratingBar1 = (RatingBar) findViewById(R.id.ratingBar1);

        ivTargetPhoto2 = (ImageView) findViewById(R.id.ivTargetPhoto2);
        txtTargetJob2 = (TextView) findViewById(R.id.txtTargetJob2);
        txtTargetName2 = (TextView) findViewById(R.id.txtTargetName2);
        txtContent2 = (EditText) findViewById(R.id.txtContent2);
        gvImageList2 = (GridView) findViewById(R.id.gvImageList2);
        imageList2 = new ArrayList<>();
        ratingBar2 = (RatingBar) findViewById(R.id.ratingBar2);

        type = getIntent().getIntExtra(KEY_TYPE,0);
        panel2 = findViewById(R.id.panel2);

        adapter1 = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageList1.size() + 1;
            }

            @Override
            public Object getItem(int i) {
                return i == getCount() - 1 ? null : imageList1.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (position < imageList1.size()){
                    convertView = inflater.inflate(R.layout.item_image, null);
                }else{
                    convertView = inflater.inflate(R.layout.item_add_image, null);
                }

                holder = new ViewHolder(convertView,0);
                holder.bind(getItem(position));

                return convertView;
            }
        };

        adapter2 = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageList2.size() + 1;
            }

            @Override
            public Object getItem(int i) {
                return i == getCount() - 1 ? null : imageList2.get(i);
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup viewGroup) {
                ViewHolder holder = null;
                if (position < imageList2.size()){
                    convertView = inflater.inflate(R.layout.item_image, null);
                }else{
                    convertView = inflater.inflate(R.layout.item_add_image, null);
                }

                holder = new ViewHolder(convertView,1);
                holder.bind(getItem(position));

                return convertView;
            }
        };

        gvImageList1.setAdapter(adapter1);
        gvImageList2.setAdapter(adapter2);
        findViewById(R.id.btnSubmit).setOnClickListener(this);
        photoPopupwindow = new SelectPhotoPopupwindow($this, this);
    }

    @Override
    public void initData() {
        if (type == 1){
            panel2.setVisibility(View.VISIBLE);
            presenter.searchProjectRolePhone($this,serviceData.getOrderCode(), new OnLoadListener() {
                @Override
                public void onLoad(Object content) {
                    if (content != null){
                        List<RoleBean.Data> list = (List<RoleBean.Data>) content;
                        if (list.size() > 0){
                            txtTargetJob1.setText(list.get(0).getRoleTypeName());
                            txtTargetName1.setText(list.get(0).getRoleName());
                            Picasso.with($this).load(FileUtils.rePath(list.get(0).getUrl()))
                                    .placeholder(R.drawable.i_head_default)
                                    .into(ivTargetPhoto1);
                            maxId1 = list.get(0).getMsId();
                            ratingBar1.setRating(5);
                            role1 = list.get(0);
                        }

                        if (list.size() > 1){
                            txtTargetJob2.setText(list.get(1).getRoleTypeName());
                            txtTargetName2.setText(list.get(1).getRoleName());
                            Picasso.with($this).load(FileUtils.rePath(list.get(1).getUrl()))
                                    .placeholder(R.drawable.i_head_default)
                                    .into(ivTargetPhoto2);
                            maxId2 = list.get(1).getMsId();
                            ratingBar2.setRating(5);
                            role2 = list.get(1);
                        }
                    }
                }
            });
        }else{
            panel2.setVisibility(View.GONE);
            presenter.searchDesignRolePhone($this,serviceData.getOrderCode(), new OnLoadListener() {
                @Override
                public void onLoad(Object content) {
                    if (content != null){
                        List<RoleBean.Data> list = (List<RoleBean.Data>) content;
                        if (list.size() > 0){
                            txtTargetJob1.setText(list.get(0).getRoleTypeName());
                            txtTargetName1.setText(list.get(0).getRoleName());
                            Picasso.with($this).load(FileUtils.rePath(list.get(0).getUrl()))
                                    .placeholder(R.drawable.i_head_default)
                                    .into(ivTargetPhoto1);
                            maxId1 = list.get(0).getMsId();
                            role1 = list.get(0);
                        }
                    }
                }
            });
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.fl_Left:
                finish();
                break;
            case R.id.btnSubmit:
                if (type == 1){
                    presenter.saveServiceAppraisePhone($this,
                            maxId1,
                            txtContent1.getText().toString(),
                            (int)ratingBar1.getRating(),
                            role1,
                            maxId2,
                            txtContent2.getText().toString(),
                            (int)ratingBar2.getRating(),
                            role2,
                            serviceData.getOrderCode(),
                            new OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {

                                }
                            });
                }else {
                    presenter.saveServiceAppraisePhone($this,
                            maxId1,
                            txtContent1.getText().toString(),
                            (int)ratingBar1.getRating(),
                            role1,
                            serviceData.getOrderCode(),
                            new OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {

                                }
                            });
                }

                break;
            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                if (ContextCompat.checkSelfPermission($this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    takePicture();
                }
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                presenter.cardSelect($this);
                break;
        }
    }

    private class ViewHolder{
        private View itemView;
        private int index;
        public ViewHolder(View itemView,int index){
            this.itemView = itemView;
            this.index = index;
        }

        public void bind(Object obj) {
            if (obj instanceof GoodsBean.Image){
                final GoodsBean.Image img = (GoodsBean.Image) obj;
                ImageView iv = (ImageView) itemView.findViewById(R.id.image);
                Picasso.with($this).load(FileUtils.rePath(img.getUrl())).into(iv);
                iv.setTag(R.id.decode,img);
                View v = itemView.findViewById(R.id.ivClose);
                v.setVisibility(View.VISIBLE);
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        presenter.deleteImage($this,img.getId(), new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                removePic(index,(int)content);
                            }
                        });
                    }
                });

                iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Utils.showPicDialog($this,FileUtils.rePath(img.getUrl()),R.drawable.i_rect_bg);
                    }
                });
            }else {
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photoPopupwindow.showAtLocation(rootView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                        currentIndex = index;
                    }
                });
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePicture();
            } else {
                Utils.showToast(this, "权限被禁止，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void removePic(int i,int id) {
        if (i == 0){
            for (GoodsBean.Image pic : imageList1){
                if (pic.getId() == id){
                    imageList1.remove(pic);
                    adapter1.notifyDataSetChanged();
                    break;
                }
            }
        }else{
            for (GoodsBean.Image pic : imageList2){
                if (pic.getId() == id){
                    imageList2.remove(pic);
                    adapter2.notifyDataSetChanged();
                    break;
                }
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode){
                case INTENT_SELECT_PIC:
                    Uri uri0 = data.getData();
                    if (currentIndex == 0){
                        presenter.doUploadPic($this,uri0,maxId1, new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                FileBean.Data img = (FileBean.Data) content;
                                GoodsBean.Image bean = new GoodsBean.Image();
                                bean.setId(img.getMallId());
                                bean.setUrl(img.getUrl());
                                imageList1.add(bean);
                                adapter1.notifyDataSetChanged();
                            }
                        });
                    }else {
                        presenter.doUploadPic($this,uri0,maxId2, new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                FileBean.Data img = (FileBean.Data) content;
                                GoodsBean.Image bean = new GoodsBean.Image();
                                bean.setId(img.getMallId());
                                bean.setUrl(img.getUrl());
                                imageList2.add(bean);
                                adapter2.notifyDataSetChanged();
                            }
                        });
                    }


                    break;

                case PHOTO_GRAPH:
                    if (data != null){
                        Bundle b = data.getExtras();
                        Bitmap bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        if (currentIndex == 0){
                            presenter.doUploadServiceEvaluate($this, bitmap, maxId1,new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    if (content != null && content instanceof FileBean.Data){
                                        FileBean.Data data = (FileBean.Data) content;
                                        GoodsBean.Image bean = new GoodsBean.Image();
                                        bean.setId(data.getMallId());
                                        bean.setUrl(data.getUrl());
                                        imageList1.add(bean);
                                        adapter1.notifyDataSetChanged();
                                    }
                                }
                            });
                        }else{
                            presenter.doUploadServiceEvaluate($this, bitmap, maxId2,new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {
                                    if (content != null && content instanceof FileBean.Data){
                                        FileBean.Data data = (FileBean.Data) content;
                                        GoodsBean.Image bean = new GoodsBean.Image();
                                        bean.setId(data.getMallId());
                                        bean.setUrl(data.getUrl());
                                        imageList2.add(bean);
                                        adapter2.notifyDataSetChanged();
                                    }
                                }
                            });
                        }

                    }else{
                        Utils.showToast($this,"请从相册选择图片");
                    }
                    break;
            }
        }
    }

    private void takePicture(){
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try{
                startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
            }catch (Exception e){
                e.printStackTrace();
                Utils.showToast($this,"请从相册上传图片");
            }
        } else
            Utils.showToast($this, "未插入SD卡");
    }
}
